package com.xyxy.platform.modules.core.utils;

import com.xyxy.platform.modules.core.utils.collections.Predicate;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Collections工具集.
 * <p/>
 * 在JDK的Collections和Guava的Collections2后, 命名为Collections3.
 * <p/>
 * 函数主要由两部分组成，一是自反射提取元素的功能，二是源自Apache Commons Collection, 争取不用在项目里引入它。
 */
public class Collections3 {

    /**
     * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
     *
     * @param collection        来源集合.
     * @param keyPropertyName   要提取为Map中的Key值的属性名.
     * @param valuePropertyName 要提取为Map中的Value值的属性名.
     */
    public static <K, V> Map<K, V> extractToMap(final Collection collection,
                                                final String keyPropertyName,
                                                final String valuePropertyName) {
        if (null == collection || collection.size() == 0) {
            return new HashMap<>();
        }
        Map<K, V> map = new HashMap<>(collection.size());

        try {
            for (Object obj : collection) {
                map.put((K) PropertyUtils.getProperty(obj, keyPropertyName),
                        (V) PropertyUtils.getProperty(obj, valuePropertyName));
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return map;
    }

    /**
     * 提取集合中的对象的属性名作为Key, 对象自身作为对象(通过Getter函数), 组合成Map.
     *
     * @param collection      来源集合.
     * @param keyPropertyName 要提取为Map中的Key值的属性名.
     */
    public static <K, V> Map<K, V> extractToMap(final V[] collection, final String keyPropertyName) {
        if (null == collection) {
            return new HashMap<>();
        }
        Map<K, V> map = new HashMap<>(collection.length);

        try {
            for (Object obj : collection) {
                map.put((K) PropertyUtils.getProperty(obj, keyPropertyName), (V) obj);
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return map;
    }

    /**
     * 提取集合中的对象的属性名作为Key, 对象自身作为对象(通过Getter函数), 组合成Map.
     *
     * @param collection      来源集合.
     * @param keyPropertyName 要提取为Map中的Key值的属性名.
     */
    public static <K, V> Map<K, V> extractToMap(final Collection<V> collection,
                                                final String keyPropertyName) {
        if (null == collection || collection.size() == 0) {
            return new HashMap<>();
        }
        Map<K, V> map = new HashMap<>(collection.size());

        try {
            for (V obj : collection) {
                map.put((K) PropertyUtils.getProperty(obj, keyPropertyName),
                        obj);
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return map;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static List extractToList(final Collection collection, final String propertyName) {
        if (null == collection || collection.size() == 0) {
            return new ArrayList();
        }
        List list = new ArrayList(collection.size());

        try {
            for (Object obj : collection) {
                Object item = PropertyUtils.getProperty(obj, propertyName);
                if (null != item) {
                    list.add(item);
                }
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static <T1, T2> List<T2> extractToList(final Iterator<T1> collection, final String propertyName) {
        ArrayList<T2> list = new ArrayList<>();

        try {
            while (collection.hasNext()) {
                T1 item = collection.next();
                Object propertyValue = PropertyUtils.getProperty(item, propertyName);
                if (null != propertyValue) {
                    list.add((T2) propertyValue);
                }
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static <T1, T2> List<T2> extractToList(final T1[] collection, final String propertyName) {
        ArrayList<T2> list = new ArrayList<>(collection.length);

        try {
            for (Object obj : collection) {
                Object item = PropertyUtils.getProperty(obj, propertyName);
                if (null != item) {
                    list.add((T2) item);
                }
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     */
    public static <T1, T2> List<T2> extractToList(final Iterator<T1> collection, final String propertyName, Predicate<T1> predicate) {
        ArrayList<T2> list = new ArrayList<>();

        try {
            while (collection.hasNext()) {
                T1 item = collection.next();
                if (null != predicate && predicate.evaluate(item)) {
                    Object propertyValue = PropertyUtils.getProperty(item, propertyName);
                    if (null != propertyValue) {
                        list.add((T2) propertyValue);
                    }
                }
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    /**
     * 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
     *
     * @param collection   来源集合.
     * @param propertyName 要提取的属性名.
     * @param separator    分隔符.
     */
    public static String extractToString(final Collection collection, final String propertyName, final String separator) {
        List list = extractToList(collection, propertyName);
        return StringUtils.join(list, separator);
    }

    /**
     * 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
     */
    public static String convertToString(final Collection collection, final String separator) {
        return StringUtils.join(collection, separator);
    }

    /**
     * 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix，后面加入postfix，如<div>mymessage</div>。
     */
    public static String convertToString(final Collection collection, final String prefix, final String postfix) {
        StringBuilder builder = new StringBuilder();
        for (Object o : collection) {
            builder.append(prefix).append(o).append(postfix);
        }
        return builder.toString();
    }

    /**
     * 判断是否为空.
     */
    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }

    /**
     * 判断是否为空.
     */
    public static boolean isEmpty(Map map) {
        return (map == null) || map.isEmpty();
    }

    /**
     * 判断是否为空.
     */
    public static boolean isNotEmpty(Collection collection) {
        return (collection != null && !(collection.isEmpty()));
    }

    /**
     * 取得Collection的第一个元素，如果collection为空返回null.
     */
    public static <T> T getFirst(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }

        return collection.iterator().next();
    }

    /**
     * 获取Collection的最后一个元素 ，如果collection为空返回null.
     */
    public static <T> T getLast(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }

        // 当类型为List时，直接取得最后一个元素 。
        if (collection instanceof List) {
            List<T> list = (List<T>) collection;
            return list.get(list.size() - 1);
        }

        // 其他类型通过iterator滚动到最后一个元素.
        Iterator<T> iterator = collection.iterator();
        while (true) {
            T current = iterator.next();
            if (!iterator.hasNext()) {
                return current;
            }
        }
    }

    /**
     * 返回a+b的新List.
     */
    public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
        List<T> result = new ArrayList<T>(a);
        result.addAll(b);
        return result;
    }

    /**
     * 返回a-b的新List.
     */
    public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
        List<T> list = new ArrayList<T>(a);
        for (T element : b) {
            list.remove(element);
        }

        return list;
    }

    /**
     * 返回a与b的交集的新List.
     */
    public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
        List<T> list = new ArrayList<T>();

        for (T element : a) {
            if (b.contains(element)) {
                list.add(element);
            }
        }
        return list;
    }

    /**
     * 将数组分割
     *
     * @param collections 原始数组
     * @param subSize     每组分割大小
     * @param <T>         数组元素对象
     * @return 返回的二维数组
     */
    public static <T> List<List<T>> split(List<T> collections, int subSize) {
        if (null == collections) {
            return null;
        }

        int total = collections.size();
        int count = (int) Math.ceil(((double) total) / subSize);

        List<List<T>> result = new ArrayList<List<T>>(count);
        if (total <= subSize) {
            result.add(new ArrayList<>(collections));
            return result;
        }
        for (int i = 0; i < count; i++) {
            int from = i * subSize;
            int to = (i + 1) * subSize;
            if (to > total) {
                to = total;
            }
            result.add(i, collections.subList(from, to));
        }
        return result;
    }

    /**
     * Map --> Bean 2: 利用 org.apache.commons.BeanUtils 工具类实现 Map --> Bean
     *
     * @param map
     * @param obj
     */
    public static void transMap2Bean2(Map<String, Object> map, Object obj) {
        if (map == null || obj == null) {
            return;
        }
        try {
            BeanUtils.populate(obj, map);
        } catch (Exception e) {
            System.out.println("transMap2Bean2 Error " + e);
        }
    }

    /**
     * Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
     *
     * @param map
     * @param obj
     */
    public static void transMap2Bean(Map<String, Object> map, Object obj) {

        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                if (map.containsKey(key)) {
                    Object value = map.get(key);
                    // 得到property对应的setter方法
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                }

            }

        } catch (Exception e) {
            System.out.println("transMap2Bean Error " + e);
        }

        return;

    }

    /**
     * Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);

                    map.put(key, value);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;

    }
}
